﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace FlashPay.DAO.Impl
{
    using FlashPay.DAO.Interface;

    using FlashPay.EF;

    using FlashPay.Entity;
    using FlashPay.Entity.Parameter;
    using FlashPay.EF.Models;
    using FlashPay.DAO.Shared;
    using FlashPay.Util;
    using FlashPay.Entity.DAORequest.User;
    using FlashPay.Entity.Response.User;
    using FlashPay.Entity.Response.Role;

    /// <summary>
    /// 用户数据接口实现
    /// </summary>
    public class UserInfoDaoImpl : BaseDAO, UserInfoDao
    {
        #region 注入
        /// <summary>
        /// EF上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="context"></param>
        public UserInfoDaoImpl(DbContext context)
        {
            _context = (FlashPayContext)context;
        }

        public UserInfoDaoImpl()
        {
            this._context = new FlashPayContext();
        }

        public void Dispose()
        {
            if (_context != null)
            {
                _context.Dispose();
            }
        }
        #endregion

        /// <summary>
        /// 根据编号获取用户
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>UserInfo</returns>
        public UserInfo Get(int id)
        {
            return _context.UserInfo.Where(x => x.UId == id).FirstOrDefault();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public UserInfo Login(string loginName)
        {
            return _context.UserInfo.Where(p => p.ULoginName == loginName).FirstOrDefault();
        }

        /// <summary>
        /// 根据编号获取用户(SQL)
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>UserInfo</returns>
        public UserInfo GetUserInfo(int id)
        {
            return _context.UserInfo.Where(x => x.UId == id).FirstOrDefault();
        }

        /// <summary>
        /// 更新用户密码
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <param name="passWord">用户密码</param>
        /// <returns></returns>
        public bool UpdatePassWord(int id, string passWord)
        {
            //官方推荐的修改方式（先查询，再修改）
            var model = _context.UserInfo.Where(p => p.UId.Equals(id)).FirstOrDefault();
            if (model != null)
            {
                model.UPwd = passWord;
                _context.SaveChangesAsync();
                return true;
            }
            else
            {
                throw new Exception("当前记录不存在！");
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="userInfo">新增对象</param>
        /// <returns></returns>
        public int Insert(UserInfo model, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);

            _flashPayContext.UserInfo.Add(model);
            _flashPayContext.SaveChanges();
            return model.UId;
        }


        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        public bool UpdateUserInfo(UserInfo model, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);

            bool result = false;

            var userInfo = _flashPayContext.UserInfo.Find(model.UId);
            if (userInfo != null)
            {
                if (!string.IsNullOrEmpty(model.UPwd))
                {
                    userInfo.UPwd = model.UPwd;
                }
                if (!string.IsNullOrEmpty(model.UEmail))
                {
                    userInfo.UEmail = model.UEmail;
                }
                if (!string.IsNullOrEmpty(model.UTelephone))
                {
                    userInfo.UTelephone = model.UTelephone;
                }
                if (!string.IsNullOrEmpty(model.UDescription))
                {
                    userInfo.UDescription = model.UDescription;
                }
                _flashPayContext.Entry<UserInfo>(userInfo);
                _flashPayContext.SaveChanges();
                result = true;
            }

            return result;
        }

        /// <summary>
        /// 更新(是否已显示过二维码)
        /// </summary>
        /// <param name="model"></param>
        public bool Update(UserInfo model)
        {
            //EF容器,并获取当前实体对象的状态管理对象
            //_context.Entry<UserInfo>(model);
            //_context.SaveChanges();
            //return true;

            var user = _context.UserInfo.Where(p => p.UId.Equals(model.UId)).FirstOrDefault();
            if (user != null)
            {
                user.UShowQR = model.UShowQR;
                return _context.SaveChanges() > 0;
            }
            return false;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public int UpdateStatus(UserInfoQuery query)
        {
            //官方推荐的修改方式（先查询，再修改）
            var model = _context.UserInfo.Where(p => p.UId == query.Id).FirstOrDefault();
            if (model != null)
            {
                model.UStatus = (sbyte)query.uStatus;
                return _context.SaveChanges();
            }
            return 0;
        }

        /// <summary>
        /// 更新谷歌验证状态
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public int ChangeLoggedIn(UserInfo query)
        {
            var model = _context.UserInfo.Where(p => p.UId == query.UId).FirstOrDefault();
            if (model != null)
            {
                model.ULoggedIn = query.ULoggedIn;
                model.USecretKey = query.USecretKey;
                if (string.IsNullOrEmpty(query.USecretKey))
                {
                    model.UShowQR = query.UShowQR;
                }
                return _context.SaveChanges();
            }
            return 0;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">系统编号</param>
        /// <returns></returns>
        public int Delete(UserInfoQuery query, FlashPayContext flashPayContext = null)
        {
            var _flashPayContext = (flashPayContext ?? _context);

            var model = _flashPayContext.UserInfo.Where(p => p.UId == query.Id).FirstOrDefault();
            if (model != null)
            {
                //需判定是否有账号管理，删除的权限
                model.UStatus = (int)Entity.Enum.UserInfoStatus.删除;
                model.ULoginName = query.uLoginName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                return _flashPayContext.SaveChanges();
            }
            return 0;
        }

        /// <summary>
        /// 获取用户下拉列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<UserInfo></returns>
        public List<UserInfo> GetList(UserInfoQuery query)
        {
            //多条件查询
            var where = PredicateBuilder.True<UserInfo>();

            //编号
            if (query.Id.HasValue)
            {
                where = where.And(c => c.UId == query.Id.Value);
            }
            //公司编号
            //if (query.CompanyId.HasValue)
            //{
            //    where = where.And(c => c.UCompanyId == query.CompanyId.Value);
            //}
            //公司编号
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                where = where.And(c => query.CompanyIds.Contains(c.UCompanyId));
            }
            //登录名称搜索
            if (!string.IsNullOrEmpty(query.uLoginName))
            {
                where = where.And(c => c.ULoginName.Contains(query.uLoginName));
            }

            var list = _context.UserInfo.Where(where.Compile()).ToList();
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserInfo></returns>
        public PagedList<UserInfo> GetPager(UserInfoQuery query)
        {
            PagedList<UserInfo> result = new PagedList<UserInfo>();

            try
            {
                var bank = from u in _context.UserInfo
                           join c in _context.Company on u.UCompanyId equals c.CompanyId
                           orderby u.UId descending
                           //where (c.CompanyPid == query.CompanyId || c.CompanyId == query.CompanyId)
                           where query.CompanyIds.Contains(u.UCompanyId)
                           select new UserInfo
                           {
                               UId = u.UId,
                               ULoginName = u.ULoginName,
                               UTelephone = u.UTelephone,
                               UStatus = u.UStatus,
                               ULoggedIn = u.ULoggedIn,
                               UShowQR = u.UShowQR,
                               UEmail = u.UEmail,
                               UDescription = u.UDescription,
                               UCompanyId = u.UCompanyId,
                               UCompany = c
                           };

                if (!string.IsNullOrEmpty(query.uLoginName))
                {
                    bank = bank.Where(c => c.ULoginName.Contains(query.uLoginName));
                }
                if (!string.IsNullOrEmpty(query.uEmail))
                {
                    bank = bank.Where(c => c.UEmail.Contains(query.uEmail));
                }
                if (!string.IsNullOrEmpty(query.uTelephone))
                {
                    bank = bank.Where(c => c.UTelephone == query.uTelephone);
                }
                if (!string.IsNullOrEmpty(query.uCompanyName))
                {
                    bank = bank.Where(c => c.UCompany.CompanyName.Contains(query.uCompanyName));
                }
                if (query.Id.HasValue)
                {
                    bank = bank.Where(c => c.UId == query.Id);
                }
                if (query.uStatus == 1 || query.uStatus == 2)
                {
                    bank = bank.Where(c => c.UStatus == query.uStatus);
                }
                bank = bank.Where(u => u.UStatus != (int)Entity.Enum.UserInfoStatus.删除);
                List<UserInfo> list = Split(bank, query.CurrentPageIndex.Value, query.PageSize.Value);
                result.TotalCount = bank.Count();
                result.TData = list;
                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.ErrorMessage = "服务器异常!";
            }
            return result;
        }

        

        //根据id集合查出用户信息
        public PagedList<UserInfo> GetUserInfoByIds(List<int> query, int pageIndex, int pageSize)
        {
            var idList = _context.UserInfo.Where(u => u.UStatus == (int)Entity.Enum.UserInfoStatus.启用 && query.Contains(u.UId));
            PagedList<UserInfo> result = new PagedList<UserInfo>();
            List<UserInfo> list = Split(idList, pageIndex, pageSize);
            result.TotalCount = list.Count();
            result.TData = list.Select(u => new UserInfo
            {
                UId = u.UId,
                ULoginName = u.ULoginName
            }).ToList();
            result.Success = true;
            return result;
        }

        //登录名是否已存在
        public bool CheckLoginName(UserInfoQuery query)
        {
            if (string.IsNullOrEmpty(query.uLoginName)) return false;
            //int status=(int)Entity.Enum.UserInfoStatus.删除;
            var checkLoginName = _context.UserInfo.Where(u => u.ULoginName == query.uLoginName
            //&& u.UStatus!= status
            ).FirstOrDefault();
            if (checkLoginName != null) return false;
            return true;
        }

        //原密码是否正确
        public bool CheckOldPwd(UserInfoQuery query)
        {
            if (string.IsNullOrEmpty(query.uPwd)) return false;
            var checkPwd = _context.UserInfo.Where(u => u.UId == query.Id && u.UPwd == EncryptHelper.enSHA256(query.uPwd)).FirstOrDefault();
            if (checkPwd == null) return false;
            return true;
        }

        //保存用户信息
        public int SaveUserInfo(UserInfo model)
        {
            if (model.UId <= 0)
            {
                _context.UserInfo.Add(model);
            }
            else
            {
                _context.UserInfo.Update(model);
            }
            return _context.SaveChanges();
        }

        /// <summary>
        /// 用戶列表
        /// </summary>
        public void Get(BaseModel<List<UserInfo>> result, UserRequest model)
        {
            /* 呼叫資料庫 */
            IQueryable<UserInfo> _result = _context.UserInfo.Where(
                user =>
                    (String.IsNullOrEmpty(model.UserName) || user.ULoginName.Contains(model.UserName)) &&
                    (model.CompanyID == null || model.CompanyID.Count == 0 || model.CompanyID.Contains(user.UCompanyId)) &&
                    (model.UserID == null || model.UserID.Count == 0 || model.UserID.Contains(user.UId)) &&
                    (model.NotUserStatus < 1 || user.UStatus != model.NotUserStatus)
            );

            List<UserInfo> list = Split(_result.OrderByDescending(user => user.UId), result.PageIndex, result.PageSize);

            /* 結果複製 */
            result.Success = true;
            result.TotalCount = _result.Count();
            result.Result = list;
        }

        /// <summary>
        /// 通过条件获取用户信息
        /// </summary>
        /// <param name="SearchValue">搜索值</param>
        /// <param name="CompanyId">公司编号</param>
        /// <returns>List<UserInfo></returns>
        public List<UserInfo> SearchUserInfo(string SearchValue, int CompanyId)
        {
            List<UserInfo> result = new List<UserInfo>();
            result = _context.UserInfo.Where(c => c.UCompanyId == CompanyId && c.ULoginName.Contains(SearchValue)).Take(10).ToList();
            return result;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserInfo></returns>
        public PagedList<UsersResponse> GetUsersPager(UsersQuery query)
        {
            var q = from u in _context.UserInfo
                    join c in _context.Company on u.UCompanyId equals c.CompanyId
                    where u.UId == query.UserId || u.UCreateId == query.UserId
                    select new
                    {
                        u.UId,
                        u.UCompanyId,
                        c.CompanyName,
                        u.ULoginName,
                        u.UTelephone,
                        u.UStatus,
                        u.ULoggedIn,
                        u.UShowQR,
                        u.UEmail,
                        u.UCreateId,
                        u.UDescription
                    };


            if (!string.IsNullOrEmpty(query.ULoginName))
            {
                q = q.Where(c => c.ULoginName.Contains(query.ULoginName));
            }

            if (!string.IsNullOrEmpty(query.UTelephone))
            {
                q = q.Where(c => c.UTelephone == query.UTelephone);
            }

            if (!string.IsNullOrEmpty(query.UCompanyName))
            {
                q = q.Where(c => c.CompanyName.Contains(query.UCompanyName));
            }

            if (query.UStatus!=null && query.UStatus.Any())
            {
                q = q.Where(c => query.UStatus.Contains(c.UStatus));
            }

            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.UCompanyId));
            }

            var list = q.Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList();
            var total = q.Count();

            #region 数据转换
            var usersResponses = new List<UsersResponse>();

            list.ForEach(item => {
                var usersResponse = new UsersResponse()
                {
                    UId = item.UId,
                    UCompanyId = item.UCompanyId,
                    UCompanyName = item.CompanyName,
                    ULoginName = item.ULoginName,
                    UTelephone = item.UTelephone,
                    UStatus = item.UStatus,
                    ULoggedIn = item.ULoggedIn,
                    UShowQR = item.UShowQR,
                    UEmail = item.UEmail,
                    UDescription = item.UDescription,
                    UCreateId = item.UCreateId,
                    CurrentLoginUserId = query.UserId,
                    IsResetPassWord = query.UserPermission.Any(p=>p.Contains("User0012"))
                };

                usersResponses.Add(usersResponse);
            });
            #endregion

            return new PagedList<UsersResponse>()
            {
                TotalCount = total,
                TData = usersResponses,
                Success = true,
            };
        }

        /// <summary>
        /// 获取公司角色
        /// </summary>
        /// <param name="companyId"></param>
        public List<RoleResponse> GetRoleList(int companyId)
        {
            var q = from sr in _context.SysRole
                    join
                    c in _context.Company on sr.RCompanyId equals c.CompanyId
                    where 
                    sr.RCompanyId == companyId
                    select new RoleResponse
                    {
                        RId = sr.RId,
                        RCompanyId = sr.RCompanyId,
                        CompanyName = c.CompanyName,
                        RName = sr.RName,
                        CreateCId =sr.CreateCid,
                        CreateDate = sr.CreateDate,
                    };


            return q.ToList();
        }


    }
}
